package com.naojump.android.twicca.picasa;

import static com.naojump.util.NUtils.hasChar;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.naojump.android.gdata.client.NClientLogin;
import com.naojump.android.gdata.util.NAuthenticationException;
import com.naojump.android.picasa.NPicasaWebAlbums;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * NLoginActivity
 * 
 * @author Naoto Murata
 * @since 2
 * @Version 8
 */
public class NLoginActivity extends Activity {

    /**
     * NLoginThread
     * 
     * @author Naoto Murata
     * @since 2
     * @Version 8
     */
    public static class NLoginThread extends Thread implements Serializable {

        /** serialVersionUID */
        private static final long serialVersionUID = 8620120780040071535L;

        /** Tag */
        private static final String TAG = NLoginThread.class.getName();

        /** Activity */
        Activity mApp;

        /** Uploaded notification handler */
        Handler mHandler;

        /**
         * Constructor
         * 
         * @param app
         *            Activity
         * @param handler
         *            Uploaded notification handler
         */
        public NLoginThread(Activity app, Handler handler) {
            mApp = app;
            mHandler = handler;
        }

        /**
         * @see java.lang.Thread#run()
         */
        @Override
        public void run() {
            if (DEBUG)
                Log.d(TAG, "run");

            Intent intent = mApp.getIntent();
            Bundle extras = intent.getExtras();

            String email = extras.getString("email");
            String password = extras.getString("password");
            String auth = extras.getString("auth");

            try {
                NClientLogin.Status status = null;
                boolean tokenHasExpired = true;
                if (hasChar(auth)) {
                    try {
                        status = new NClientLogin.Status(200, auth, true);
                        NPicasaWebAlbums lh2 = new NPicasaWebAlbums(
                                NPicasaWebAlbums.USER_ID_DEFAULT, status);
                        lh2.getAlbums(NPicasaWebAlbums.ACCESS_PRIVATE);
                        tokenHasExpired = false;
                    } catch (NAuthenticationException e) {
                        // Do nothing.
                        // Token has expired.
                    }
                }
                if (tokenHasExpired) {
                    status = NClientLogin.auth(TAG,
                            NClientLogin.ACCT_TYPE_HOSTED_OR_GOOGLE, email,
                            password, NPicasaWebAlbums.SERVICE_NAME, TAG);
                }
                intent.putExtra("status", status);
            } catch (Exception e) {
                intent.putExtra("exception", e);
            }

            mHandler.sendEmptyMessage(0);
        }

    }

    /** DEBUG */
    private static final boolean DEBUG = false;

    /** Tag */
    private static final String TAG = NLoginActivity.class.getName();

    /** Executor service */
    ExecutorService mExec;

    /** Logged in notification handler */
    private Handler mHandler;

    /** Logging in dialog */
    private ProgressDialog mDlg;

    /**
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (DEBUG)
            Log.d(TAG, "onCreate");

        mDlg = new ProgressDialog(this);
        mDlg.setTitle(R.string.app_name);
        mDlg.setMessage(getString(R.string.logging_in));
        mDlg.setButton(DialogInterface.BUTTON_POSITIVE,
                getString(R.string.abort),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mExec.shutdownNow();
                        dialog.dismiss();
                        finish();
                    }
                });
        mDlg.show();

        if (getLastNonConfigurationInstance() == null) {
            mExec = Executors.newSingleThreadExecutor();
            mHandler = new Handler() {

                @SuppressWarnings("synthetic-access")
                @Override
                public void handleMessage(Message msg) {
                    mDlg.dismiss();
                    mExec.shutdown();
                    setResult(msg.what, getIntent());
                    finish();
                }
            };
            mExec.submit(new NLoginThread(this, mHandler));
        } else {
            Map<String, Object> b = (Map<String, Object>) getLastNonConfigurationInstance();
            mExec = (ExecutorService) b.get("mExec");
            mHandler = (Handler) b.get("mHandler");
        }
    }

    /**
     * @see android.app.Activity#onRetainNonConfigurationInstance()
     */
    @Override
    public Object onRetainNonConfigurationInstance() {
        if (DEBUG)
            Log.d(TAG, "onRetainNonConfigurationInstance");

        Map<String, Object> b = new HashMap<String, Object>();
        b.put("mExec", mExec);
        b.put("mHandler", mHandler);
        return b;
    }

}
